# -*- coding: utf-8 -*-
# -*- frozen_string_literal: true -*-
require "<%= @scaffold.gem_path %>/manifest"
require "<%= @scaffold.gem_path %>/version"
require "digest/sha2"

module PrepRelease
def self.package
# Unless many tasks require cleaning stuff don't require "rake/clean"
# More tasks make `rake -T` less readable.

# system calls not unit-tested
old_gem = Dir["#{gem_name}-*.gem"].first.to_s

File.delete(old_gem) if File.exist? old_gem
system "gem", "build", "#{gem_name}"
end


def self.checksum gem, archive:
filename = File.basename(gem) + ".sha512"
checksum = Digest::SHA512.new.hexdigest(File.read(gem))

File.open(File.join(archive, filename), "w") { |f| f.write checksum }
checksum
end

def self.commit_checksum archive:
fail "Must create checksum file before trying to do commit" unless checksum_in?(archive)

# system calls not unit-tested
nothing_staged = system "git", "diff", "--staged", "--exit-code", out: "/dev/null"
fail "Can't commit checksum when there are staged elements" unless nothing_staged

system "git", "add", checksum_file_under(archive)
system "git", "commit", %Q[--message="Add checksum for version #{version}"]
end

def self.tag_release_commit archive:
fail "Must add checksum before tagging a release" unless checksum_in?(archive)

# system calls not unit-tested
system "git", "tag", "--annotate", "v#{version}",
%Q[--message="Release #{version}"]
end

def self.publish_gem
# system calls not unit-tested
system "git", "push", "--follow-tags"
system "gem", "push", "#{built_gem}"
end

private

def self.checksum_in? archive
File.exist? checksum_file_under(archive)
end

def self.checksum_file_under archive
"#{archive}/#{built_gem}.sha512"
end

def self.built_gem
"#{gem_name}-#{version}.gem"
end

def self.gem_name
<%= @scaffold.namespace %>::Manifest.gem_name
end

def self.version
<%= @scaffold.namespace %>::Version
end
end
